
'''The URL+(HTTP|HTTPS)+json interface to the Plurk service.'''

import simplejson as json
import sys

class BadRequestError(Exception): pass

class FailToConnectError(Exception): pass

class PlurkAPI:
  '''An abstract URL+(HTTP|HTTPS)+json interface to Plurk.'''

  def __init__(self, api_key, api_url='http://www.plurk.com/API',
               debug_level=0):
    self._api_key = api_key
    self._debug_level = debug_level
    colon = api_url.find('://')
    if colon == -1:
      self._base_url = api_url
    else:
      self._base_url = api_url[colon:]

  def _MakeUrl(self, path, encrypt=False):
    '''Construct the URL for connecting to Plurk API.
    Args:
    '''
    if encrypt:
      return ''.join(['https', self._base_url, path])
    else:
      return ''.join(['http', self._base_url, path])

  def __call__(self, path, encrypt, **kw):
    '''Call a Plurk API and return the response body as a string.

    This function does not raise exceptions.

    Args:
      path: The API function path to call.
      encrypt: use HTTPS to connect to plurk if True, else use HTTP.
      kw: the POST parameters to send.
    Returns:
      status_code [int]: The http status code, or -1 if connection failed.
      response [string]: The response body, or '' if connection failed..
    '''
    if 'api_key' not in kw.keys(): kw['api_key'] = self._api_key
    url = self._MakeUrl(path, encrypt)
    self._Connect(url, **kw)
    return self.GetStatusCode(), self.GetBody()

  def _Connect(self, url, **kw):
    '''Make an http(s) connection to a URL with an optional dict of POST data.
    
    Subclasses must implement this function.'''
    raise NotImplementedError

  def GetCookies(self):
    raise NotImplementedError

  def GetBody(self):
    raise NotImplementedError

  def GetStatusCode(self):
    raise NotImplementedError

  def GetErrorMessage(self):
    raise NotImplementedError
